package com.atguigu.service.impl;

import java.util.Date;

import com.atguigu.dao.BookDao;
import com.atguigu.dao.OrderDao;
import com.atguigu.dao.OrderItemDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.dao.impl.OrderDaoImpl;
import com.atguigu.dao.impl.OrderItemDaoImpl;
import com.atguigu.pojo.Book;
import com.atguigu.pojo.CardItem;
import com.atguigu.pojo.Cart;
import com.atguigu.pojo.Order;
import com.atguigu.pojo.OrderItem;
import com.atguigu.service.OrderService;
import com.jhlabs.composite.DarkenComposite;

public class OrderServiceImpl implements OrderService {

	private OrderDao orderDao = null;
	private OrderItemDao orderItemDao = null;
	private BookDao bookDao = null;
	
	public OrderServiceImpl() {
		orderDao = new OrderDaoImpl();
		orderItemDao = new OrderItemDaoImpl();
		bookDao = new BookDaoImpl();
	}
	
	@Override
	public String saveOrder(Cart cart, int userId) {
		//订单号
		String orderId = System.currentTimeMillis() + "" + userId;
		Order order = new Order(orderId, new Date(), cart.getTotalPrice(), 0, userId);
		orderDao.saveOrder(order);
		
		for (CardItem cartItem : cart.getItems().values()) {
			//生成每个订单项
			OrderItem orderItem = new OrderItem(0, cartItem.getName(), cartItem.getCount(),
					cartItem.getPrice(), cartItem.getPriceCount(), orderId); 
			orderItemDao.saveOrderItem(orderItem);
			
			//int i = 9/0;
			//查询购买的商品 
			Book book = bookDao.queryBookOne(cartItem.getId());
			book.setSales(book.getSales() + cartItem.getCount());
			
			int stock = book.getStock() - cartItem.getCount();
			//if(stock > 0) {
				book.setStock(stock);
			//}else {
				//break;
			//}
			
			
			bookDao.update(book);
			
		}
		//清空购物车
		cart.clear();
		return orderId;
	}

}
